package com.ctshk.rpc.system.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.rpc.system.dto.CaptchaDTO;
import com.ctshk.rpc.system.service.IValidateService;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 谢诗宏
 * @description 验证码业务类
 * @date 2020/12/16
 */
@Slf4j
@DubboService
public class ValidateServiceImpl implements IValidateService {

    @Value("${auth.user.captcha.timeout}")
    private Long captchaTimeout;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result<CaptchaDTO> getCode() {
        CaptchaDTO data = new CaptchaDTO();
//        String uuid = UUID.randomUUID().toString(true);
        String uuid = IdUtil.simpleUUID();
        //SpecCaptcha captcha = new SpecCaptcha(120, 40);
        //String text = captcha.text();// 获取运算的结果：5
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        // 获取运算的结果：5
        String text = captcha.text();
        log.info("登录验证码key[{}],验证码code[{}]", uuid, text);
        redisTemplate.opsForValue().set(RedisConstants.CAPTCHA_KEY + uuid, text, captchaTimeout, TimeUnit.MINUTES);
        data.setKey(uuid);
        data.setCodeUrl(captcha.toBase64());
        return Result.success(data);
    }

    @Override
    public void check(String key, String code) {

        if (StringUtils.isBlank(code)) {
            throw new BusinessException(SystemError.USER_1007);
        }
        Object codeFromRedis = redisTemplate.opsForValue().get(RedisConstants.CAPTCHA_KEY + key);
        if (codeFromRedis == null) {
            throw new BusinessException(SystemError.USER_1005);
        }
        if (!Objects.equals(code, String.valueOf(codeFromRedis))) {
            throw new BusinessException(SystemError.USER_1006);
        }

//        redisTemplate.delete(RedisConstants.CAPTCHA_KEY + key);
    }
}
